<template>
  <el-dialog v-model="dialogVisible" title="新增负责人" width="600">
    <el-form
      ref="formRef"
      :model="form"
      label-width="auto"
      label-position="right"
      class="demo-form-inline"
      :rules="formRules"
      status-icon
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="submit">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { formRules } from "./rules.js";
import { addCategory, setCategory } from "@/api/category.ts";

const dialogVisible = ref(false);

const form = ref({
  name: ""
});
const isEdit = ref();
const formRef = ref();

const submit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        await setCategory({
          ...form.value
        });
      } else {
        await addCategory({
          ...form.value
        });
      }
      closeDialog();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 打开对话框
const openDialog = async (row = undefined) => {
  dialogVisible.value = true;
  await nextTick();
  formRef.value.resetFields();
  isEdit.value = row ? true : false;
  if (row) {
    form.value = { ...row };
  }
};

const emits = defineEmits(["closeDialogEvent"]);
const closeDialog = () => {
  dialogVisible.value = false;
  emits("closeDialogEvent");
};

defineExpose({
  openDialog
});
</script>

<style lang="less" scoped></style>
